package org.micode.common.utils;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class YamlUtils {

    public static final YamlUtils instance = new YamlUtils();

    private static Map<String, Map<String, Object>> ymlMap = new HashMap<>();

    static {
        Yaml yaml = new Yaml();
        try (InputStream in = YamlUtils.class.getClassLoader().getResourceAsStream("application.yml");) {
            ymlMap = yaml.loadAs(in, HashMap.class);
        } catch (Exception ignore) {
            ;
        }
    }

    public String getValue(String key) {
        String separator = ".";
        String[] separatorKeys = null;
        if (key.contains(separator)) {
            separatorKeys = key.split("\\.");
        } else {
            return ymlMap.get(key).toString();
        }
        Map<String, Object> finalValue = new HashMap<>();
        for (int i = 0; i < separatorKeys.length - 1; i++) {
            if (i == 0) {
                finalValue = (Map) ymlMap.get(separatorKeys[i]);
                continue;
            }
            if (finalValue == null) {
                break;
            }
            finalValue = (Map) finalValue.get(separatorKeys[i]);
        }

        if (null != finalValue) {
            String k = separatorKeys[separatorKeys.length - 1];
            return finalValue.get(k).toString();
        }
        return null;
    }

}
